import sys
import os
import random
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *

class Demo(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        mainLayout = QVBoxLayout()  

        toolBar =QToolBar()
        
        btn = QPushButton('Add')
        btn.clicked.connect(self.OnAddClicked)
        toolBar.addWidget(btn)

        btn = QPushButton('Insert')
        btn.clicked.connect(self.OnInsertClicked)
        toolBar.addWidget(btn)

        btn = QPushButton('Delete')
        btn.clicked.connect(self.OnDelClicked)
        toolBar.addWidget(btn)

        toolBar.addWidget(QLabel('Update:'))
        self.currentEdit = QLineEdit()
        toolBar.addWidget(self.currentEdit)
        btn = QPushButton('Update')
        btn.clicked.connect(self.OnUpdateClicked)
        toolBar.addWidget(btn)    

        toolBar.addWidget(QLabel('Keyword:'))
        self.keyEdit = QLineEdit()
        toolBar.addWidget(self.keyEdit)
        btn = QPushButton('Search')
        btn.clicked.connect(self.OnSearchClicked)
        toolBar.addWidget(btn)
        
        self.listView = QListView()        
        self.listData = QStandardItemModel()        
        self.listView.setModel(self.listData)
        
        mainLayout.addWidget(toolBar)
        mainLayout.addWidget(self.listView)
        self.setLayout(mainLayout) 
    
    def OnAddClicked(self):
        txt = f'Value{random.randint(0, 999)}'
        self.listData.appendRow(QStandardItem(txt))
        self.parent.OnShowMessage(f"Add item '{txt}',count {self.listData.rowCount()}'")        
    def OnInsertClicked(self):
        txt = f'Value{random.randint(0, 999)}'
        row =self.listView.currentIndex().row()
        if row ==-1:
            row=0
        self.listData.insertRow(row,QStandardItem(txt))
        self.parent.OnShowMessage(f"Insert item '{txt}' at {row},count {self.listData.rowCount()}")        
    def OnDelClicked(self):
        index =self.listView.currentIndex()
        self.parent.OnShowMessage(f"Delete item '{self.listData.itemFromIndex(index).text()}'")
        self.listData.removeRow(index.row())
    def OnUpdateClicked(self):
        index =self.listView.currentIndex()
        old = self.listData.itemFromIndex(index).text()
        new = self.currentEdit.text()
        self.listData.setItem(index.row(),index.column(),QStandardItem(new))
        self.parent.OnShowMessage(f"Update item from '{old}' to '{new}'")
    def OnSearchClicked(self):
        keyword = self.keyEdit.text()
        msg = f"Searh keyword '{keyword}' result '"
        for item in self.listData.findItems(keyword,Qt.MatchFlag.MatchContains):
            msg += f'{item.text()},'
        msg+="'"
        self.parent.OnShowMessage(msg)
def runDemo(parent):
    wigdet =  Demo(parent)
    return wigdet